<?php

$dir = Yii::getPathOfAlias('ext') . DIRECTORY_SEPARATOR . 'phpmailer' . DIRECTORY_SEPARATOR;
require_once $dir . 'class.phpmailer.php';
require_once $dir . 'class.smtp.php';

class SendMail {
    public $subject;
    public $to;
    public $replyTo;
    public $bcc;
    public $content;
    public $attachedFile;
    
    public $params; //info of STMP server
    public $errors;
    private $mailerObj;
    
    public function __construct($sub, $to, $content) {
        $this->subject = $sub;
        $this->to      = $to;
        $this->content = $content;
        $this->params = Yii::app()->params['stmp_configuration'];
        
        //initialize phpmailer
        $this->mailerObj = new PHPMailer();
        $this->setConfiguration();
    }
    
    public function send() {
        //========================= Email body =========================
        if (empty($this->subject)) {
            $this->mailerObj->Subject  = $this->params['default_subject'] . ' ' . date('Y-m-d');
        } else {
            $this->mailerObj->Subject  = $this->subject;
        }

        if (empty($this->to)) {
            $receiver = $this->params['default_receiver'];
            if (is_array($receiver)) {
                foreach ($receiver as $value) {
                    $this->mailerObj->AddAddress($value);
                }
            } else {
                $this->mailerObj->AddAddress($receiver);
            }
        } else {
            $this->mailerObj->AddAddress($this->to);
        }
        
        if (! empty($this->replyTo)) {
            $this->mailerObj->AddReplyTo($this->replyTo);
        }
        
        $this->mailerObj->MsgHTML($this->content);
        //========================= //Email body =========================
        
        //attached file
        if ( ! empty($this->attachedFile) ) {
            $this->mailerObj->AddAttachment($this->attachedFile->tempName, $this->attachedFile->name);
        }

        if (! $this->mailerObj->Send()) {
            $this->errors = $this->mailerObj->ErrorInfo;
            return FALSE;
        } else {
            return TRUE;
        }
    }
    
    private function setConfiguration() {
        $this->mailerObj->SMTPDebug = 1;
        $this->mailerObj->IsSMTP();
        $this->mailerObj->SMTPAuth = true;
        $this->mailerObj->Host     = $this->params['domain'];
        $this->mailerObj->Port     = $this->params['port'];
        $this->mailerObj->SMTPSecure = "tls"; //Gmail

        $this->mailerObj->Username = $this->params['username'];
        $this->mailerObj->Password = $this->params['password'];
        $this->mailerObj->From     = $this->params['username'];
        $this->mailerObj->FromName = $this->params['from_name'];
        $this->mailerObj->IsHTML(true);
        $this->mailerObj->CharSet = 'utf-8';
    }
}